//
//  GoodManagerMainVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/9/21.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "GoodManagerMainVC.h"
#import "GoodManagerMainModel.h"
#import "GoodManagerMainCell.h"
#import "GoodManagerAddVC.h"
#import "GoodAttributeListVC.h"
#import "GoodManagerModifyVC.h"

@interface GoodManagerMainVC ()<UITableViewDelegate,UITableViewDataSource> {
    int page;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <GoodManagerMainModel *>*array;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation GoodManagerMainVC

-(NSMutableArray<GoodManagerMainModel *> *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - 64 - BottomHeight)];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page = 1;
            [strongSelf requestForList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
    }
    return _tableView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, (_bottomView.nim_width - 30 - 15 - 30) * 0.5, 44)];
        [nextBtn setBackgroundColor:HexColorA(0x3D68EB, 0.1)];
        nextBtn.layer.masksToBounds = YES;
        nextBtn.layer.cornerRadius = 6;
        [nextBtn setTitle:@"属性模板" forState:0];
        [nextBtn setTitleColor:HexColor(0x3D68EB) forState:0];
        nextBtn.titleLabel.font = BoldFontOfSize(16);
        [nextBtn addTarget:self action:@selector(muBanClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:nextBtn];
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(nextBtn.nim_right + 15, 10, nextBtn.nim_width, 44)];
        [saveBtn setBackgroundColor:Color_ThemeColor];
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 6;
        [saveBtn setTitle:@"添加货物" forState:0];
        [saveBtn setTitleColor:HexColor(0xffffff) forState:0];
        saveBtn.titleLabel.font = BoldFontOfSize(16);
        [saveBtn addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:saveBtn];
    }
    return _bottomView;
}

- (void)muBanClick {
    GoodAttributeListVC *vc = [GoodAttributeListVC new];
    [self.rt_navigationController pushViewController:vc animated:YES];
}

- (void)addClick {
    GoodManagerAddVC *vc = [GoodManagerAddVC new];
    [self.rt_navigationController pushViewController:vc animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"货物管理";
    page = 1;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self requestForList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList) name:ReceiptDeliveryRefreshGoodManagerList object:nil];
}

- (void)refreshList {
    page = 1;
    [self requestForList];
}

- (void)requestForList {
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerList params:@{@"page":@(page)} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.array removeAllObjects];
                self.array = [GoodManagerMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            }else {
                NSArray *array = [GoodManagerMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.array addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GoodManagerMainCell *cell = [GoodManagerMainCell GoodManagerMainCellWithTableView:tableView];
    GoodManagerMainModel *model = self.array[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.deleteBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定删除？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself requestForDelete:model.Id IndexPath:indexPath];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    
        }];
        [alert addAction:sureAction];
        [alert addAction:cancleAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    };
    return cell;
}

- (void)requestForDelete:(NSString *)Id IndexPath:(NSIndexPath *)indexPath {
    //1=启用，2=禁用，3=删除
    [HttpRequest PostWithApi:ReceiptDeliveryGoodManagerDeleteGood params:@{@"id":Id} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已删除"];
            [self.array removeObjectAtIndex:indexPath.row];
            [self.tableView beginUpdates];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GoodManagerMainCell *cell = [GoodManagerMainCell GoodManagerMainCellWithTableView:tableView];
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GoodManagerMainModel *model = self.array[indexPath.row];
    GoodManagerModifyVC *vc = [GoodManagerModifyVC new];
    vc.Id = model.Id;
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
